<?php
class Ddup_Tags_Model_Resource_Popular_Collection extends Mage_Tag_Model_Resource_Popular_Collection
{
	public function joinFields($storeId = 0)
    {
    	$category = $this->getCurrentCategory();
   		$productCollection = $category->getProductCollection();
   		$productIds = array();
   		foreach ($productCollection as $product) {
   			$productIds[$product['entity_id']] = $product['entity_id'];
   		}
        $select = $this->getSelect()
            ->reset()
            ->from(
                array('tag_summary' => $this->getTable('tag/summary')),
                array('popularity' => 'tag_summary.popularity'))
            ->joinInner(
                array('tag' => $this->getTable('tag/tag')),
                'tag.tag_id = tag_summary.tag_id AND tag.status = ' . Mage_Tag_Model_Tag::STATUS_APPROVED)
            ->joinInner(
            	array('tag_relation' => $this->getTable('tag/relation')),
            	'tag.tag_id = tag_relation.tag_id',null)
            ->where('tag_relation.product_id IN (?)',$productIds)
            ->where('tag_summary.store_id = ?', $storeId)
            ->where('tag_summary.products > ?', 0)
            ->order('popularity ' . Varien_Db_Select::SQL_DESC)
            ->distinct();
        return $this;
    }
    
	public function getCurrentCategory()
    {
		if (Mage::registry('current_category')) {
        	$category = Mage::registry('current_category');
		} else {
			$category = Mage::getModel('catalog/category')->load(Mage::app()->getStore()->getRootCategoryId());
		}

        return $category;
    }
}